import { log } from "node:console";
import { createServer } from "node:http";
import express, { Request, Response } from "express";
import { Server as SocketIOServer } from "socket.io";

const PORT = process.env.PORT || 3000;

// 1. 创建 HTTP 服务器, 将 express 应用作为请求监听器
const app = express();
const httpServer = createServer(app);

// 2. 创建 Socket.IO 实例，并绑定到 http server .
const io = new SocketIOServer(httpServer, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"],
  },
});

// 3. 编写 Socket.IO　服务器端逻辑
io.on("connection", (socket) => {
  log(`Client connected: ${socket.id}`);

  // 3.1. 监听客户端发送的 "message"
  socket.on("message", (msg) => {
    log(`Received message from client: ${msg}`);
    io.emit("message", `Server received message: ${msg}`);
  });
  // 3.2. 监听客户端发送的 "disconnect"
  socket.on("disconnect", () => {
    log(`Client disconnected: ${socket.id}`);
    io.emit("client-disconnected", socket.id);
  });

  // 3.3 每隔 5 秒向客户端发送一个 'ping' 消息
  setInterval(() => {
    socket.emit("ping", "Server ping!");
  }, 5000);

  //3.4 监听 'message' 事件
  socket.on("message", (msg: string) => {
    console.log(`Message from ${socket.id}: ${msg}`);
    // 广播消息给所有连接的客户端
    io.emit("message", `${socket.id}: ${msg}`);
    // 或广播给除自发送者之外的所有客户端
    socket.broadcast.emit("message", `${socket.id}: ${msg}`);

  });
});

app.get("/", (req: Request, res: Response) => {
  res.send("<h1>Hello World</h1> by express with TS. **");
});

// 4. 启动 HTTP 服务器
httpServer.listen(PORT, () => {
  log(`Server is running on port ${PORT}`);
});
